package darkwindclient.connection;

import java.io.IOException;
import java.io.InputStream;

import darkwindclient.gui.TextField;

/**
 * @author Jacob Ferm
 */
public class Reader extends Thread {

	private InputStream is;
	private TextField text;
	private TextField log;

	public Reader(InputStream inputStream, TextField text, TextField log) {
		is = inputStream;
		this.text = text;
		this.log = log;
	}

	public void run() {
		try {
			int c;
			String colorCode = "";
			while ((c = is.read()) != -1) {
				if (c == 27) {
					if ((c = is.read()) != '[') {
						System.out.println("[ error " + (int) c);
						continue;
					}
					while ((c = is.read()) != 'm') {
						colorCode += (char) c;
						if (colorCode.length() > 2) {
							System.out.println("ERROR");
							break;
						}
					}
					text.updateStyle(Integer.parseInt(colorCode));
					log.updateStyle(Integer.parseInt(colorCode));
					colorCode = "";
				} else if (c == 255) {
					// telnet commands. skipped for now
					c = is.read();
					c = is.read();
				} else {
					text.print((char) c);
					log.print((char) c);

				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
